package org.example;
import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/updateProductServlet")
public class updateProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String productId = request.getParameter("id"); // 获取商品 ID
        String productName = request.getParameter("product_name"); // 获取商品名
        String price = request.getParameter("price"); // 获取价格
        String description = request.getParameter("description"); // 获取描述
        String star = request.getParameter("star"); // 获取积分
        String imagePath = request.getParameter("image_path"); // 获取图片路径

        DB DB = new DB();
        try (Connection conn = DB.createConn()) {
            String sql = "UPDATE products SET product_name = ?, price = ?, description = ?, star = ?, image_path = ? WHERE id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, productName);
                pstmt.setString(2, price);
                pstmt.setString(3, description);
                pstmt.setString(4, star);
                pstmt.setString(5, imagePath);
                pstmt.setString(6, productId);

                int rows = pstmt.executeUpdate();
                if (rows > 0) {
                    ResponseUtils.sendResponse(response, "修改商品成功！", "productPage.jsp");
                } else {
                    ResponseUtils.sendResponse(response, "修改商品失败！", "productPage.jsp");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "系统错误，请稍后重试！", "productPage.jsp");
        }
    }
}
